package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper  apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
           //1.检查参数
        if (dto == null &&
                StringUtils.isBlank(dto.getPhone()) &&
                StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
            // 2 判断手机号登录 设备登录
        if (StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
            //2.1 手机号登录， 根据手机号查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在！");
            }
            //2.2 获取用户密码 （mm+salt）
            String dbpassword = apUser.getPassword();
            String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());

            if (!dbpassword.equals(newPwd)){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号或密码错误");
            }
            //2.2 成功 则生成jwt令牌
            HashMap<Object, Object> resultMap = new HashMap<>();
            resultMap.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setPhone("");
            apUser.setPassword("");
            resultMap.put("user",apUser);
            //2.3 返回数据
            return ResponseResult.okResult(resultMap);
        }else {
            //3 设备登录 直接生成默认的jwt令牌
            HashMap<Object, Object> resultMap = new HashMap<>();
            resultMap.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(resultMap);
        }
    }
}
